<template>
  <div class="p-table">
    <el-table
      ref="table"
      v-loading="loading"
      highlight-current-row
      :row-key="rowKey"
      :show-summary="showSummary"
      :summary-method="summarMethod"
      border
      fit
      max-height="550"
      style="width: 100%"
      :span-method="spanMethod"
      :data="dataSource"
      :tree-props="treeProps"
      @selection-change="handleSelectionChange"
      @sort-change="sortChange"
    >
      <slot name="selection" />
      <template v-for="(item, index) in columns">
        <template v-if="!item.customRender">
          <el-table-column
            :key="'info-' + index"
            :class="item.className"
            :label="item.label"
            :sortable="item.sortable"
            :prop="item.prop"
            :type="item.type"
            :fixed="item.fixed"
            :align="item.align"
            :width="item.width"
            :min-width="item.minWidth"
            :column-key="item.columnKey"
            :data="item.data"
            :show-overflow-tooltip="true"
            :reserve-selection="item.reserveSelection"
          />
        </template>

        <template v-else>
          <el-table-column
            :key="index"
            :class="item.className"
            :label="item.label"
            :sortable="item.sortable"
            :prop="item.prop"
            :fixed="item.fixed"
            :type="item.type"
            :align="item.align"
            :width="item.width"
            :min-width="item.minWidth"
            :column-key="item.columnKey"
            :data="item.data"
            :reserve-selection="item.reserveSelection"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="{ row }">
              <jx-table :tags="item.customRender(row, row[item.prop], item)" />
            </template>
          </el-table-column>
        </template>
      </template>
      <slot name="operation" />
    </el-table>
    <pagination
      v-show="newPagination.total > 0"
      :total="newPagination.total"
      :page-sizes="newPagination.pageSizeOptions"
      :page.sync="newPagination.pageNum"
      :limit.sync="newPagination.pageSize"
      @pagination="paginationChangeFn"
    />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import jxTable from './jxTable'
// import { Store } from 'vuex'
export default {
  name: '',
  components: {
    Pagination,
    jxTable
  },
  props: {
    treeProps: {
      type: Object,
      default: function() {
        return {}
      }
    },
    queryParams: {
      type: Object,
      default: function() {
        return {
          createTimeFrom: '',
          createTimeTo: ''
        }
      }
    },
    showSummary: {
      type: Boolean,
      default: false
    },
    summarMethod: {
      type: Function,
      default: function() {
        return function() {}
      }
    },
    rowKey: {
      type: [String, Function],
      default: null
    },
    data: {
      type: Array,
      default: function() {
        return []
      }
    },
    spanMethod: {
      type: Function,
      default: function() {
        return function() {}
      }
    },
    isFetch: {
      type: Boolean,
      default: false
    },
    urlName: {
      type: String,
      default: ''
    },
    delUrlName: {
      type: String,
      default: ''
    },
    expUrlName: {
      type: String,
      default: ''
    },
    selectionChange: {
      type: Function,
      default: function() {}
    },
    pagination: {
      type: Object,
      default: function() {
        return {
          pageSizeOptions: [10, 20, 30, 40, 100],
          total: 0,
          pageNum: 1,
          pageSize: 10
        }
      }
    },
    columns: {
      type: Array,
      default: function() {
        return []
      }
    },
    listTypes: {
      type: Array,
      default: function() {
        return []
      }
    },
    // 删除提示语
    tips: {
      type: String,
      default:
        '确定删除所选中的数据? 当您点击确定按钮后，这些数据将会被彻底删除'
    }
  },
  data() {
    return {
      dataSource: [],
      sort: {},
      selectedRowKeys: [],
      tempRowKeys: [],
      loading: false,
      newPagination: {
        pageSizeOptions: [10, 20, 30, 40, 100],
        // 总条数
        total: 0,
        // 当前页数
        pageNum: 1,
        // 每页条数
        pageSize: 10
      },
      dataTypes: []
    }
  },
  watch: {
    pagination: function(n) {
      this.newPagination = n
    },
    data: function(n) {
      this.dataSource = n
    }
  },
  mounted() {
    if (!this.isFetch) {
      this.search()
    } else {
      this.dataSource = this.data
    }
    this.dataTypes = this.listTypes
  },
  methods: {
    toggleRowSelection(row) {
      this.$refs['table'].toggleRowSelection(row, true)
    },
    paginationChangeFn(e, r) {
      this.newPagination.pageNum = e.page
      this.newPagination.pageSize = e.limit
      this.fetch({ ...this.queryParams, ...this.sort })
    },
    search() {
      this.newPagination.pageSize = this.pagination.pageSize
      this.newPagination.pageNum = this.pagination.pageNum
      this.newPagination.pageSizeOptions = this.pagination.pageSizeOptions
      var params = {
        pageSize: this.newPagination.pageSize,
        pageNum: this.newPagination.pageNum
      }
      // 删除空或者undefined的查询字段
      for (const i in this.queryParams) {
        if (!this.queryParams[i] && this.queryParams[i] !== 0) {
          delete this.queryParams[i]
        }
      }
      this.fetch({
        ...params,
        ...this.queryParams,
        ...this.sort
      })
      // this.fetch()
    },
    handleSelectionChange(val) {
      this.selectedRowKeys = val
      this.selectionChange && this.selectionChange(val)
      this.$emit('selection-change', val)
    },
    clearSelection() {
      this.$refs.table.clearSelection()
    },
    fetch(params = {}) {
      params.pageSize = this.newPagination.pageSize
      params.pageNum = this.newPagination.pageNum
      this.loading = true
      this.$get(this.urlName, {
        ...params
        // ...this.queryParams,
        // ...this.sort
      })
        .then((r) => {
          // const data = this.urlName === 'socket/groups' ? r.data.data : r.data
          const data = r.data.data
          const pagination = { ...this.newPagination }
          pagination.total = data.total
          if (Array.isArray(data)) {
            this.dataSource = data || []
          } else {
            if (data.data) {
              this.dataSource = data.data.rows || []
            } else {
              data.rows.forEach((el) => {
                if (el['formValue']) {
                  el['formValue'] = JSON.parse(el['formValue'])
                  el['formValue'].forEach((item) => {
                    el[item.controlId] = item.controlValue
                  })
                }
              })
              this.dataSource = data.rows || []
            }
          }
          this.$nextTick(() => {
            if (this.tempRowKeys.length) {
              this.tempRowKeys.forEach((el) => {
                this.dataSource.forEach((item, i) => {
                  if (el.id === item.id) {
                    this.toggleRowSelection(this.dataSource[i])
                  }
                })
              })
            }
            this.tempRowKeys = []
          })
          this.newPagination = pagination
          this.loading = false
        })
        .then(() => {
          for (const i in this.dataSource) {
            if (this.dataTypes && this.dataTypes.length > 0) {
              for (const k in this.dataSource[i]) {
                for (const j in this.dataTypes) {
                  for (const n in this.dataTypes[j]) {
                    if (n === k) {
                      this.dataSource[i][k] =
                        this.dataTypes[j][k][this.dataSource[i][k]]
                    }
                  }
                }
              }
            }
          }
        })
    },
    sortChange(val) {
      this.sort.field = val.prop
      this.sort.order = val.order
      this.search()
    },
    reset(params) {
      // 取消选中
      this.selectedRowKeys = []
      // 重置分页
      this.newPagination.pageSize = this.pagination.pageSize
      this.newPagination.pageNum = this.pagination.pageNum
      this.newPagination.pageSizeOptions = this.pagination.pageSizeOptions
      this.sort = {}
      this.$refs.table.clearSort()
      this.$refs.table.clearFilter()
      this.fetch(params)
    },
    // 删除
    batchDelete(options) {
      const delField = options && options.delField ? options.delField : 'id'
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的数据')
        return
      }
      const that = this
      this.$confirm(that.tips, '提示')
        .then(() => {
          that
            .$delete(
              that.delUrlName +
                '/' +
                that.selectedRowKeys.map((el) => el[delField]).join(',')
            )
            .then((r) => {
              if (r && r.data && r.data.data.length !== 0) {
                that.$message.error(r.data.message)
                that.selectedRowKeys = []
                that.clearSelection()
                return
              }
              that.$message.success((options && options.msg) || '删除成功')
              that.selectedRowKeys = []
              that.search()
              options && options.callback && options.callback()
            })
        })
        .catch(() => {
          that.selectedRowKeys = []
          that.clearSelection()
        })
    },
    // 导出Excel
    exportExcel() {
      this.$export(this.expUrlName, {
        ...this.queryParams
      })
    },
    getData() {
      return this.dataSource || []
    }
  }
}
</script>
